pipeline {

  agent {
    node {
      label 'sshpass'
    }
  }

  environment {
     MODULE_NAME = "server/${projectCode}-web "
     IMAGE_URL= "10.6.64.142/mining/$BRANCH_NAME/${projectCode}"
     HOST = sh(returnStdout: true,script: ''' if [ $BRANCH_NAME = dev ]; then echo "开发环境IP"; else echo "测试IP"; fi  ''').trim()
     SSH_ID = sh(returnStdout: true,script: ''' if [ $BRANCH_NAME = dev ]; then echo "开发环境秘钥"; else echo "测试环境秘钥"; fi  ''').trim()
  }

  options { buildDiscarder(logRotator(numToKeepStr: '5')) }

  stages {
    stage('Maven Package') {
      steps {
        container('jdk21') {
          sh "/opt/maven/bin/mvn clean package '-Dmaven.test.skip=true' -pl $MODULE_NAME -am"
        }
      }
    }

    stage('Docker Build') {
      steps {
        container('jnlp') {
          sh '''
           cd $MODULE_NAME
           docker build -t  $IMAGE_URL:$BUILD_NUMBER .
          '''
        }
      }
    }

    stage('Docker Push') {
      steps {
        container('jnlp') {
          withCredentials([usernamePassword(credentialsId: 'harbor-admin', passwordVariable: 'DOCKER_PASSWORD', usernameVariable: 'DOCKER_USERNAME')]) {
            sh '''
              echo "$DOCKER_PASSWORD" | docker login 10.6.64.142 -u "$DOCKER_USERNAME" --password-stdin
              docker push  $IMAGE_URL:$BUILD_NUMBER
            '''
          }
        }
      }
    }

    stage('docker compose Publish') {
      steps {
        container('sshpass') {
        withCredentials([usernamePassword(credentialsId: env.SSH_ID, passwordVariable: 'PASSWORD', usernameVariable: 'USERNAME')]) {
            sh '''
              cd $MODULE_NAME
              <#noParse>sed -i s#{BRANCH_NAME}#$BRANCH_NAME#g docker-compose.yml
              sed -i s#{BUILD_NUMBER}#$BUILD_NUMBER#g  docker-compose.yml</#noParse>

              sshpass -p ${r"${PASSWORD}"}  ssh -o StrictHostKeyChecking=no   -tt ${r"${USERNAME}"}@${r"${HOST}"} 'mkdir -p /data/docker-compose/business'
              sshpass -p ${r"${PASSWORD}"}  ssh  -tt ${r"${USERNAME}"}@${r"${HOST}"} 'rm -f  /data/docker-compose/business/${projectCode}.yml'
              sshpass -p ${r"${PASSWORD}"}  scp docker-compose.yml ${r"${USERNAME}"}@${r"${HOST}"}:/data/docker-compose/business/${projectCode}.yml
              sshpass -p ${r"${PASSWORD}"}  ssh  -tt ${r"${USERNAME}"}@${r"${HOST}"} 'docker compose -f  /data/docker-compose/business/${projectCode}.yml up -d'
            '''
        }
        }
      }
    }

  }

}
